package middle

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

type Mongo struct {
	client *mongo.Client
}

// NewMongo 创建一个Mongo对象
func NewMongo(address, user, password string) (*Mongo, error) {
	// 使用 options.Credential 指定认证信息
	clientOptions := options.Client().ApplyURI(address).SetAuth(options.Credential{Username: user, Password: password})
	// 连接到MongoDB
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		return nil, err
	}

	return &Mongo{client: client}, nil
}

// Close 关闭MongoDB连接
func (m *Mongo) Close() error {
	return m.client.Disconnect(context.TODO())
}

func (m *Mongo) AggregateSelect(database, collection string, pipeline ...bson.M) ([]map[string]any, error) {

	db := m.client.Database(database)
	coll := db.Collection(collection)

	// 执行聚合查询
	cursor, err := coll.Aggregate(context.TODO(), pipeline, options.Aggregate().SetAllowDiskUse(true))
	if err != nil {
		return nil, err
	}
	defer cursor.Close(context.TODO())

	var results []map[string]any
	// 遍历
	for cursor.Next(context.TODO()) {
		var result bson.M
		if err = cursor.Decode(&result); err != nil {
			log.Println("Decode error:", err)
			continue
		}
		results = append(results, result)
	}
	return results, cursor.Err()
}
